package servlet;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;

import entity.User;
import session.UserDao;
import utility.ResizeImage;

/**
 * Kontroler koji omogućava menjanje profila korisnika
 * @author jung & rigo
 *
 */
public class EditProfile extends HttpServlet {
	private static final long serialVersionUID = 531395085730230215L;
	
	@EJB
	protected UserDao userDao ; 
	 
	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			if(request.getSession().getAttribute("user")==null){
				response.sendRedirect(response.encodeURL("./login.jsp"));
				return;
			}
			String firstName = null, lastName=null, email=null, phone=null, passOld=null, passNew=null, passNew2=null;
			User usr = (User)request.getSession().getAttribute("user");
			String avatar = null;
			HashMap<String, String> fieldValues = new HashMap<String, String>();
			ServletRequestContext ctx = new ServletRequestContext(request);
			if (ServletFileUpload.isMultipartContent(ctx)) {
				try {
					// Create a factory for disk-based file items
					DiskFileItemFactory factory = new DiskFileItemFactory();
					// Set factory constraints
					factory.setSizeThreshold(2000000);
					// Create a new file upload handler
					ServletFileUpload upload = new ServletFileUpload(factory);
					// Set overall request size constraint
					upload.setSizeMax(3000000);
					// Parse the request
					List items = upload.parseRequest(request);
					// Process the uploaded items
					Iterator iter = items.iterator();
					while (iter.hasNext()) {
						FileItem item = (FileItem) iter.next();
						if (item.isFormField()) {
							String name = item.getFieldName();
							String value = item.getString();
							fieldValues.put(name, value);
						} else {
							if(item!=null){
								String contentType = item.getContentType();
								String ext = "";
								if (contentType.equalsIgnoreCase("image/gif")) {
									ext = ".gif";
								} else if (contentType
										.equalsIgnoreCase("image/jpeg")) {
									ext = ".jpg";
								} else if (contentType
										.equalsIgnoreCase("image/png")) {
									ext = ".png";
								} else {
									item.delete();
									continue;
								}
								String fileName = UUID.randomUUID().toString()
										+ ext;
								long sizeInBytes = item.getSize();
								if (sizeInBytes != 0) {
									File uploadedFile = new File(
											getServletContext().getRealPath("")
													+ "/avatar/" + fileName);
									item.write(uploadedFile);
									ResizeImage.Resize(uploadedFile, 80, 80);
									avatar = fileName;
								}
							}
						}
					}
				} catch (Exception ex) {
					System.out.println("FileUpload failed!");
				}
				email = fieldValues.get("email");
				passOld = fieldValues.get("passOld");
				passNew = fieldValues.get("passNew");
				passNew2 = fieldValues.get("passNew2");
				firstName = fieldValues.get("firstName");
				lastName = fieldValues.get("lastName");
				phone = fieldValues.get("phone");
			}
			
			if(firstName != null && !"".equalsIgnoreCase(firstName.trim()))
				usr.setFirstName(firstName);
					
			if(lastName != null && !"".equalsIgnoreCase(lastName.trim()))
				usr.setLastName(lastName);	
				
			if(email != null && !"".equalsIgnoreCase(email.trim()))
				usr.setEmail(email);
			
			if(phone != null && !"".equalsIgnoreCase(phone.trim()))
				usr.setPhone(phone);
			
			if (passOld!=null && passOld.equals(usr.getPassword())) {
				if(passNew!=null && passNew2!=null) {
					if (passNew.equals(passNew2)) {
						usr.setPassword(passNew);
					} else {
						request.setAttribute("error", "pwdErr");
						getServletContext().getRequestDispatcher("/editProfile.jsp").forward(request, response);
						return;
					}
				}
			}
			
			
			if(avatar!=null && !"".equalsIgnoreCase(avatar)) {
				usr.setAvatar(avatar);
			}
			userDao.merge(usr);
			request.setAttribute("error", "noErr");
			getServletContext().getRequestDispatcher("/editProfile.jsp").forward(request, response);
			return;
		}catch (Exception e) {
			e.printStackTrace();
		}
		response.sendRedirect(response.encodeURL("./login.jsp"));
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
